import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/closure_appointment_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_equipment_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_plan_view_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_region_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_currency_emergency_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_closure/common/access_control_dialog.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_closure/task_appointment_review/common_approval_list/common_approval_list_controller.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_emergency/common/approval_people_widget.dart';
import 'package:get/get.dart';

class CommonApprovalDetailsController extends GetxController {
  /// 预约类型 0：人员 1：普通车辆 2：危化车辆
  late int type;

  /// 外部列表controller
  final taskController = Get.find<CommonApprovalListController>();

  /// 数据实体
  late ClosureAppointmentEntity item;

  /// 流程执行实体
  ProcessCurrencyEmergencyEntity executeEntity = ProcessCurrencyEmergencyEntity();

  /// 下一个节点的执行人 有则修改，空则不管
  List<RolePersonnelEntity> nextNodeExecutor = [];

  /// 是否为结束节点的前一个节点
  bool last = false;

  /// 是不是详情页面
  bool isDetails = false;

  /// 审批流程数据
  List<ProcessNodesEntity>? nodeList;

  @override
  void onInit() {
    super.onInit();
    final Map<String, dynamic> arguments = Get.arguments as Map<String, dynamic>;
    try {
      // 获取类型
      type = arguments['type'] as int;

      item = arguments['item'] as ClosureAppointmentEntity;

      last = arguments['last'] as bool;

      isDetails = arguments['isDetails'] as bool;
    } catch (e) {
      AppLogger.printLog(e.toString());
    }
    // 初始化数据
    initData();
  }

  /// 初始化审批流程数据
  Future<void> initData() async {
    // 获取审批流程数据
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(
      Interface.queryNodeData,
      queryParameters: {'id': item.id},
    ).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        nodeList = result.data!;
        update();
      }
    });
  }

  /// 输入回调
  void onOpinion(String value) {
    executeEntity.approvalOpinions = value;
    update();
  }

  /// 签字回调
  void onSign(String url) {
    executeEntity.approvalUser = url;
  }

  /// 操作回调
  /// [type]1:通过 2:驳回 驳回即为不通过
  Future<void> onOperation(int type) async {
    // 当前执行节点
    final implementNode = taskController.implementNode;
    // 是否为结束节点的前一个节点
    final last = taskController.last;
    executeEntity.id = item.id;
    executeEntity.last = last;
    executeEntity.nodeId = implementNode.nodeId!;
    executeEntity.rtNodeId = implementNode.id!;
    executeEntity.processEncoding = implementNode.processEncoding!;
    executeEntity.rtemplateId = implementNode.rtemplateId!;
    executeEntity.status = type;
    // 如果为通过
    if (type == 1) {
      // 如果不为最后一个节点,需要选择下一个节点执行人
      if (!last) {
        // 选择执行人
        //弹出选择负责人弹窗
        Get.dialog<bool>(
          ApprovalPeopleWidget(
            type: '8',
            nextNodeExecutor: nextNodeExecutor,
            callback: () async {
              Get.back();
              executeEntity.nextNodeExecutor = nextNodeExecutor;
              emergencyExecute(type);
            },
          ),
        );
      } else {
        //弹出区域门禁授权弹窗页面
        Get.dialog<bool>(
          AccessControlDialog(
            reservationType: this.type,
            callback: (value) {
              final valueMap = value;
              // 选中的区域
              final List<GateRegionEntity> selectedRegion = valueMap['selectedRegion'] as List<GateRegionEntity>;
              // 选中的门禁
              final List<GateEquipmentEntity> selectedAccessControl = valueMap['selectedAccessControl'] as List<GateEquipmentEntity>;
              // 选中的图影
              final List<GatePlanViewEntity> selectedFigureShadow = valueMap['selectedFigureShadow'] as List<GatePlanViewEntity>;
              // 选中的部门
              final List<DepartmentTreeEntity> selectedDepartment = valueMap['selectedDepartment'] as List<DepartmentTreeEntity>;
              // 区域id
              final List<String> regions = selectedRegion.map((item) => item.id).toList();
              // 设备门禁id
              final List<String> equipmentIds = selectedAccessControl.map((item) => item.id).toList();
              // 	企业平面图id
              final List<String> views = selectedFigureShadow.map((item) => item.id).toList();
              // 如果为危化车辆且部门不为空
              if (this.type == 2 && selectedDepartment.isNotEmpty) {
                executeEntity.auditDepartment = selectedDepartment.first.getId();
              }
              executeEntity.regions.addAll(regions);
              executeEntity.equipmentIds.addAll(equipmentIds);
              executeEntity.views.addAll(views);
              emergencyExecute(type);
            },
          ),
        );
      }
    } else {
      emergencyExecute(type);
    }
  }

  /// 执行流程
  Future<void> emergencyExecute(int type) async {
    // 执行审批流程
    // 调用流程节点执行接口
    final res = await HttpUtil().generatePostRequest(Interface.closureCheck, data: executeEntity.toJson()).execute(isShowLoading: true);
    res.onSuccess((result) {
      Get.back();
      final taskController = Get.find<CommonApprovalListController>();
      taskController.refreshPage();
      AppToast.showWarning('执行成功!');
    });
    res.onError((result) {
      AppToast.showWarning('执行失败!');
    });
  }
}
